<template>
    <div class="farming-info">
        <!-- 养殖信息 -->
        <div class="info-section">
            <div class="section-header">
                <h3>养殖信息</h3>
                <el-button @click="openFarmingEdit">设置</el-button>
            </div>
            <div class="info-display">
                <div class="info-column">
                    <div class="info-item">品种：{{ localFarmingInfo.breed_Type }}</div>
                    <div class="info-item">饲养天数：{{ localFarmingInfo.feeding_Days }} 天</div>
                    <div class="info-item">饲养负责人：{{ localFarmingInfo.breeding_Supervisor }}</div>
                </div>
                <div class="info-column">
                    <div class="info-item">来源：{{ localFarmingInfo.source_Origin }}</div>
                    <div class="info-item">饲料品牌：{{ localFarmingInfo.feed_Brand }}</div>
                    <div class="info-item">出栏日期：{{ localFarmingInfo.release_Date.substring(0,
                        19).replace('T', '').replace('Z', '') }}</div>
                </div>
            </div>
        </div>

        <!-- 保健信息 -->
        <div class="vaccine-section">
            <div class="section-header">
                <h3>保健信息</h3>
                <el-button @click="addVaccineRow" type="primary">新增行</el-button>
            </div>
            <el-table :data="vaccineData" style="width: 100%; margin-top: 16px;">
                <el-table-column label="饲养天数" width="120">
                    <template #default="scope">
                        {{ scope.row?.feedingDays || scope.row?.feeding_Days || scope.row?.days || '' }}
                    </template>
                </el-table-column>
                <el-table-column label="保健方式">
                    <template #default="scope">
                        {{ scope.row?.immune_System || '' }}
                    </template>
                </el-table-column>
                <el-table-column label="保健方法">
                    <template #default="scope">
                        {{ scope.row?.immune_Methods || '' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                    <template #default="scope">
                        <el-button size="small" @click="editVaccine(scope.row, scope.$index)"
                            :disabled="!scope.row">修改</el-button>
                        <el-button size="small" type="danger" @click="deleteVaccine(scope.$index)"
                            :disabled="!scope.row">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 动检证 -->
        <div class="certificate-section">
            <div class="section-header">
                <h3>动检证</h3>
            </div>
            <div class="upload-area">
                <MultiImageUpload :model-value="localCertificateImgs" :max-count="5" :upload-text="'上传动检证'"
                    :traceability-id="props.traceabilityId" field-type="certificate"
                    @update:model-value="updateCertificateImgs" @upload-success="onCertificateUploadSuccess"
                    @remove="onCertificateRemove" />
            </div>
        </div>

        <!-- 企业信息 -->
        <div class="enterprise-section">
            <div class="section-header">
                <h3>企业信息</h3>
                <el-button @click="openEnterpriseEdit">设置</el-button>
            </div>
            <div class="info-display">
                <div class="info-item">养殖场：{{ enterpriseInfo.livestock_Farm || '四川锦祥养殖基地' }}</div>
                <div class="info-item">负责人：{{ enterpriseInfo.farm_Manage || 'X总' }}</div>
                <div class="info-item">存栏数量：{{ enterpriseInfo.nventory_Quantity || '3200' }} 只</div>
            </div>
        </div>

        <!-- 企业照片 -->
        <div class="photos-section">
            <div class="section-header">
                <h3>企业照片</h3>
            </div>
            <div class="upload-area">
                <MultiImageUpload :model-value="localEnterprisePhotoImgs" :max-count="5" :upload-text="'上传企业照片'"
                    :traceability-id="props.traceabilityId" field-type="enterprise"
                    @update:model-value="updateEnterprisePhotoImgs" @upload-success="onEnterprisePhotoUploadSuccess"
                    @remove="onEnterprisePhotoRemove" />
            </div>
        </div>

        <!-- 养殖信息编辑弹窗 -->
        <el-dialog v-model="farmingEditVisible" title="养殖信息" width="500px">
            <el-form :model="farmingForm" label-width="100px">
                <el-form-item label="品种：">
                    <el-input v-model="farmingForm.breed_Type" placeholder="请输入品种名称" />
                </el-form-item>
                <el-form-item label="来源：">
                    <el-input v-model="farmingForm.source_Origin" placeholder="请输入来源信息" />
                </el-form-item>
                <el-form-item label="饲养天数：">
                    <el-input v-model="farmingForm.feeding_Days" placeholder="请输入饲养天数" />
                </el-form-item>
                <el-form-item label="饲料品牌：">
                    <el-input v-model="farmingForm.feed_Brand" placeholder="请输入饲料品牌" />
                </el-form-item>
                <el-form-item label="饲养负责人：">
                    <el-input v-model="farmingForm.breeding_Supervisor" placeholder="请输入饲养负责人" />
                </el-form-item>
                <el-form-item label="出栏日期：">
                    <el-date-picker v-model="farmingForm.release_Date" type="date" placeholder="请选择出栏日期" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="farmingEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveFarmingInfo">保存</el-button>
            </template>
        </el-dialog>

        <!-- 企业信息编辑弹窗 -->
        <el-dialog v-model="enterpriseEditVisible" title="企业信息" width="500px">
            <el-form :model="enterpriseForm" label-width="120px">
                <el-form-item label="养殖场：">
                    <el-input v-model="enterpriseForm.livestock_Farm" placeholder="请输入养殖场名称" />
                </el-form-item>
                <el-form-item label="负责人：">
                    <el-input v-model="enterpriseForm.farm_Manage" placeholder="请输入负责人姓名" />
                </el-form-item>
                <el-form-item label="存栏数量(只)：">
                    <el-input v-model="enterpriseForm.nventory_Quantity" placeholder="请输入存栏数量" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="enterpriseEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEnterpriseInfo">保存</el-button>
            </template>
        </el-dialog>

        <!-- 保健信息编辑弹窗 -->
        <el-dialog v-model="vaccineEditVisible" title="保健信息" width="500px">
            <el-form :model="vaccineForm" label-width="100px">
                <el-form-item label="饲养天数：">
                    <el-input v-model="vaccineForm.feedingDays" placeholder="请输入饲养天数" />
                </el-form-item>
                <el-form-item label="保健方式：">
                    <el-input v-model="vaccineForm.immune_System" placeholder="请输入保健方式" />
                </el-form-item>
                <el-form-item label="保健方法：">
                    <el-input v-model="vaccineForm.immune_Methods" placeholder="请输入保健方法" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="vaccineEditVisible = false">取消</el-button>
                <el-button type="primary" @click="saveVaccineInfo">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Write, Read } from '@/components/Http/axiosHepler';
import MultiImageUpload from '@/components/MultiImageUpload.vue';
import { Location } from '@element-plus/icons-vue';
import { useCounterStore } from "@/stores/counter"
import { useRoute, useRouter } from 'vue-router';
import router from '@/router';

const Router = useRouter();
const Route = useRoute();
const store = useCounterStore();

// 定义props
const props = defineProps<{
    traceabilityId: number;
    farmingInfo: any;
    enterpriseInfo: any;
    certificateImgs: string[];
    enterprisePhotoImgs: string[];
}>();

// 定义emits
const emit = defineEmits<{
    'update:farmingInfo': [value: any];
    'update:enterpriseInfo': [value: any];
    'update:certificateImgs': [value: string[]];
    'update:enterprisePhotoImgs': [value: string[]];
    'certificate-remove': [index: number, image: any];
    'enterprise-photo-remove': [index: number, image: any];
}>();

const farmingEditVisible = ref(false);
const enterpriseEditVisible = ref(false);
const vaccineEditVisible = ref(false);
const currentEditIndex = ref(-1); // 当前编辑的行索引
const currentEditId = ref(''); // 当前编辑的记录ID

// 本地图片数组，用于v-model
const localCertificateImgs = ref<string[]>([]);
const localEnterprisePhotoImgs = ref<string[]>([]);

// 本地养殖信息数据
const localFarmingInfo = ref({
    "breedingId": "",
    "breed_Type": "",
    "source_Origin": "",
    "feeding_Days": "",
    "feed_Brand": "",
    "breeding_Supervisor": "",
    "release_Date": "",
    "traceabilityId": "",
});

// 保健信息数据
const vaccineData = ref<any[]>([
    { feedingDays: '35', immune_System: '兔瘟单苗', immune_Methods: '皮下注射' },
    { feedingDays: '40', immune_System: '巴二联苗', immune_Methods: '皮下注射' }
]);

// 保健信息编辑表单
const vaccineForm = reactive({
    feedingDays: '',
    immune_System: '',
    immune_Methods: ''
});

// 监听props变化，同步到本地数据
watch(() => props.certificateImgs, (newVal) => {
    localCertificateImgs.value = [...newVal];
}, { immediate: true });

watch(() => props.enterprisePhotoImgs, (newVal) => {
    localEnterprisePhotoImgs.value = [...newVal];
}, { immediate: true });

// 获取养殖信息
const getFarmingInfo = () => {
    Read.get('/Breeding/BreedingShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('养殖信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            // 更新本地数据
            const data = res.data.data;
            // 如果是数组，取第一个元素
            const farmingData = Array.isArray(data) ? data[0] : data;

            if (farmingData) {
                Object.assign(localFarmingInfo.value, {
                    breedingId: farmingData.breedingId || '',
                    breed_Type: farmingData.breed_Type || '',
                    source_Origin: farmingData.source_Origin || '',
                    feeding_Days: farmingData.feeding_Days || '',
                    feed_Brand: farmingData.feed_Brand || '',
                    breeding_Supervisor: farmingData.breeding_Supervisor || '',
                    release_Date: farmingData.release_Date || '',
                    traceabilityId: farmingData.traceabilityId || props.traceabilityId
                });
                console.log('更新后的本地数据:', localFarmingInfo.value);
                // 通知父组件更新
                emit('update:farmingInfo', localFarmingInfo.value);
            }
        } else {
            console.log('接口返回数据为空或状态码不是200');
        }
    }).catch(err => {
        console.error('获取养殖信息失败:', err);
        ElMessage.error('获取养殖信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 获取企业信息
const getEnterpriseInfo = () => {
    console.log('开始获取企业信息，traceabilityId:', props.traceabilityId);
    if (!props.traceabilityId) {
        console.warn('traceabilityId为空，无法获取企业信息');
        return;
    }

    Read.get('/Breeding/CompanyShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('企业信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            // 更新本地数据
            const data = res.data.data;
            const enterpriseData = Array.isArray(data) ? data[0] : data;

            if (enterpriseData) {
                const updatedInfo = {
                    livestock_Farm: enterpriseData.livestock_Farm || '',
                    farm_Manage: enterpriseData.farm_Manage || '',
                    nventory_Quantity: enterpriseData.nventory_Quantity || ''
                };
                console.log('更新后的企业信息:', updatedInfo);
                // 通知父组件更新
                emit('update:enterpriseInfo', updatedInfo);
            }
        } else {
            console.log('接口返回数据为空或状态码不是200');
        }
    }).catch(err => {
        console.error('获取企业信息失败:', err);
        ElMessage.error('获取企业信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 获取保健信息
const getVaccineInfo = () => {
    console.log('开始获取保健信息，traceabilityId:', props.traceabilityId);
    if (!props.traceabilityId) {
        console.warn('traceabilityId为空，无法获取保健信息');
        vaccineData.value = [];
        return;
    }

    Read.get('/Breeding/ImmuneShow', {
        params: {
            TraceabilityId: props.traceabilityId
        }
    }).then(res => {
        console.log('保健信息接口返回:', res.data);
        if (res.data.code === 200 && res.data.data) {
            // 确保数据是数组格式
            const data = Array.isArray(res.data.data) ? res.data.data : [res.data.data];
            console.log('处理后的保健信息数据:', data);
            vaccineData.value = data;
            console.log('更新后的保健信息:', vaccineData.value);
        } else {
            console.log('接口返回数据为空或状态码不是200');
            vaccineData.value = []; // 清空数据
        }
    }).catch(err => {
        console.error('获取保健信息失败:', err);
        ElMessage.error('获取保健信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
        vaccineData.value = []; // 出错时清空数据
    });
};

// 更新图片数组的方法
const updateCertificateImgs = (newImgs: string[]) => {
    localCertificateImgs.value = newImgs;
    emit('update:certificateImgs', newImgs);
};

const updateEnterprisePhotoImgs = (newImgs: string[]) => {
    localEnterprisePhotoImgs.value = newImgs;
    emit('update:enterprisePhotoImgs', newImgs);
};

// 养殖信息
const farmingForm = reactive({
    "breedingId": "",
    "breed_Type": "",
    "source_Origin": "",
    "feeding_Days": "",
    "feed_Brand": "",
    "breeding_Supervisor": "",
    "release_Date": "",
    "traceabilityId": "",
});

// 企业信息
const enterpriseForm = reactive({
    livestock_Farm: '',
    farm_Manage: '',
    nventory_Quantity: ''
});

// 打开养殖信息编辑
const openFarmingEdit = () => {
    Object.assign(farmingForm, localFarmingInfo.value);
    farmingEditVisible.value = true;
};

// 保存养殖信息
const saveFarmingInfo = () => {
    // 验证必填字段
    const missingFields = [];

    if (!farmingForm.breed_Type) missingFields.push('品种');
    if (!farmingForm.source_Origin) missingFields.push('来源');
    if (!farmingForm.feeding_Days) missingFields.push('饲养天数');
    if (!farmingForm.feed_Brand) missingFields.push('饲料品牌');
    if (!farmingForm.breeding_Supervisor) missingFields.push('饲养负责人');
    if (!farmingForm.release_Date) missingFields.push('出栏日期');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        traceabilityId: props.traceabilityId,
        breed_Type: farmingForm.breed_Type,
        source_Origin: farmingForm.source_Origin,
        feeding_Days: farmingForm.feeding_Days,
        feed_Brand: farmingForm.feed_Brand,
        breeding_Supervisor: farmingForm.breeding_Supervisor,
        release_Date: farmingForm.release_Date,
        createName: store.CurrentLogin?.userNickName || '',
        updateName: store.CurrentLogin?.userNickName || ''
    };

    console.log('发送保存请求:', payload);

    Write.post('/Breeding/BreedingCreate', payload).then(res => {
        console.log('保存响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            Object.assign(localFarmingInfo.value, {
                breedingId: res.data.data?.breedingId || '',
                breed_Type: farmingForm.breed_Type,
                source_Origin: farmingForm.source_Origin,
                feeding_Days: farmingForm.feeding_Days,
                feed_Brand: farmingForm.feed_Brand,
                breeding_Supervisor: farmingForm.breeding_Supervisor,
                release_Date: farmingForm.release_Date,
                traceabilityId: props.traceabilityId
            });
            console.log('保存后更新本地数据:', localFarmingInfo.value);
            // 通知父组件更新
            emit('update:farmingInfo', localFarmingInfo.value);
            farmingEditVisible.value = false;
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getFarmingInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存养殖信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 打开企业信息编辑
const openEnterpriseEdit = () => {
    Object.assign(enterpriseForm, props.enterpriseInfo);
    enterpriseEditVisible.value = true;
};

// 保存企业信息
const saveEnterpriseInfo = () => {
    // 验证必填字段
    const missingFields = [];

    if (!enterpriseForm.livestock_Farm) missingFields.push('养殖场');
    if (!enterpriseForm.farm_Manage) missingFields.push('负责人');
    if (!enterpriseForm.nventory_Quantity) missingFields.push('存栏数量');

    if (missingFields.length > 0) {
        ElMessage.error(`请填写以下必填字段：${missingFields.join('、')}`);
        return;
    }

    const payload = {
        traceabilityId: props.traceabilityId,
        livestock_Farm: enterpriseForm.livestock_Farm,
        farm_Manage: enterpriseForm.farm_Manage,
        nventory_Quantity: enterpriseForm.nventory_Quantity,
        createName: store.CurrentLogin?.userNickName || '',
        updateName: store.CurrentLogin?.userNickName || ''
    };

    console.log('发送保存企业信息请求:', payload);

    Write.post('/Breeding/CompanyCreate', payload).then(res => {
        console.log('保存企业信息响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            const updatedInfo = {
                livestock_Farm: enterpriseForm.livestock_Farm,
                farm_Manage: enterpriseForm.farm_Manage,
                nventory_Quantity: enterpriseForm.nventory_Quantity
            };
            console.log('保存后更新企业信息:', updatedInfo);
            // 通知父组件更新
            emit('update:enterpriseInfo', updatedInfo);
            enterpriseEditVisible.value = false;
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getEnterpriseInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存企业信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 保健信息相关
const addVaccineRow = () => {
    // 清空表单
    Object.assign(vaccineForm, {
        feedingDays: '',
        immune_System: '',
        immune_Methods: ''
    });
    currentEditIndex.value = -1; // 重置编辑索引，表示新增
    currentEditId.value = ''; // 重置编辑ID，表示新增
    vaccineEditVisible.value = true;
};



const editVaccine = (row: any, index: number) => {
    if (!row) {
        ElMessage.error('无效的数据行');
        return;
    }

    // 处理不同的字段名
    const formData = {
        feedingDays: row.feedingDays || row.feeding_Days || row.days || '',
        immune_System: row.immune_System || row.vaccineMethod || row.vaccine_Method || row.method || '',
        immune_Methods: row.immune_Methods || row.vaccineProcedure || row.vaccine_Procedure || row.procedure || ''
    };
    Object.assign(vaccineForm, formData);

    // 保存当前编辑的行索引和ID
    currentEditIndex.value = index;
    currentEditId.value = row.ImmuneId || row.immuneId || row.id || row.immune_Id || '';
    vaccineEditVisible.value = true;
};

const deleteVaccine = (index: number) => {
    if (index < 0 || index >= vaccineData.value.length) {
        ElMessage.error('无效的索引');
        return;
    }

    const vaccine = vaccineData.value[index];
    if (!vaccine) {
        ElMessage.error('无效的数据');
        return;
    }

    // 显示确认对话框
    ElMessageBox.confirm(
        '确定要删除这条保健信息吗？',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 检查是否有ID字段（可能是ImmuneId、immuneId、id或其他）
        const vaccineId = vaccine.ImmuneId || vaccine.immuneId || vaccine.id || vaccine.immune_Id;

        // 如果没有ID，直接删除本地数据
        if (!vaccineId) {
            vaccineData.value.splice(index, 1);
            ElMessage.success('删除成功');
            return;
        }

        // 调用删除API
        Write.post('/Breeding/ImmuneUpdate', {
            ImmuneId: vaccineId,
            isDeleted: true,
            updateName: store.CurrentLogin?.userNickName || ''
        }).then(res => {
            console.log('删除保健信息响应:', res.data);
            if (res.data.code == 200) {
                vaccineData.value.splice(index, 1);
                ElMessage.success('删除成功');
            } else {
                ElMessage.error(res.data.message || '删除失败');
            }
        }).catch(err => {
            console.error('删除保健信息失败:', err);
            ElMessage.error('删除失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
        });
    }).catch(() => {
        // 用户取消删除
        ElMessage.info('已取消删除');
    });
};

// 保存保健信息
const saveVaccineInfo = () => {
    // 验证必填字段
    if (!vaccineForm.feedingDays || !vaccineForm.immune_System || !vaccineForm.immune_Methods) {
        ElMessage.error('请填写完整的保健信息');
        return;
    }



    const payload: any = {
        traceabilityId: props.traceabilityId,
        feedingDays: vaccineForm.feedingDays,
        immune_System: vaccineForm.immune_System,
        immune_Methods: vaccineForm.immune_Methods,
        // 尝试不同的字段名
        feeding_Days: vaccineForm.feedingDays,
        immune_Method: vaccineForm.immune_System,
        immune_Procedure: vaccineForm.immune_Methods,
        createName: store.CurrentLogin?.userNickName || '',
        updateName: store.CurrentLogin?.userNickName || ''
    };

    // 如果是编辑模式，添加ID字段
    if (currentEditIndex.value >= 0 && currentEditId.value) {
        payload.ImmuneId = currentEditId.value;
    }

    console.log('发送保存保健信息请求:', payload);

    // 根据是新增还是编辑选择不同的接口
    const apiUrl = currentEditIndex.value >= 0 ? '/Breeding/ImmuneXiugai' : '/Breeding/ImmuneCreate';

    Write.post(apiUrl, payload).then(res => {
        console.log('保存保健信息响应:', res.data);
        if (res.data.code == 200) {
            // 更新本地数据
            const newVaccine = res.data.data;
            if (newVaccine) {
                // 如果是编辑现有行
                if (currentEditIndex.value >= 0 && currentEditIndex.value < vaccineData.value.length) {
                    vaccineData.value[currentEditIndex.value] = newVaccine;
                } else {
                    // 如果是新增，添加到数组末尾
                    vaccineData.value.push(newVaccine);
                }
            }
            console.log('保存后更新本地保健信息:', vaccineData.value);
            vaccineEditVisible.value = false;
            currentEditIndex.value = -1; // 重置编辑索引
            currentEditId.value = ''; // 重置编辑ID
            ElMessage.success('保存成功');
            // 重新获取数据确保同步
            getVaccineInfo();
        } else {
            ElMessage.error(res.data.message || '保存失败');
        }
    }).catch(err => {
        console.error('保存保健信息失败:', err);
        ElMessage.error('保存失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
};

// 图片上传事件处理
const onCertificateUploadSuccess = async (image: any) => {
    console.log('动检证上传成功:', image);

    // 图片已经通过 uploadHelper.ts 保存到数据库
    // MultiImageUpload组件会自动管理图片列表，这里不需要额外处理
    if (image && image.url) {
        console.log('动检证图片URL:', image.url);
        ElMessage.success('动检证上传完成');
    }
};

const onCertificateRemove = async (index: number, image: any) => {
    console.log('动检证删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要触发父组件的删除事件，让父组件知道有删除操作
    emit('certificate-remove', index, image);

    // 延迟一下再显示消息，避免与MultiImageUpload的消息冲突
    setTimeout(() => {
        ElMessage.success('动检证删除完成');
    }, 100);
};

const onEnterprisePhotoUploadSuccess = async (image: any) => {
    console.log('企业照片上传成功:', image);

    // 图片已经通过 uploadHelper.ts 保存到数据库
    // MultiImageUpload组件会自动管理图片列表，这里不需要额外处理
    if (image && image.url) {
        console.log('企业照片URL:', image.url);
        ElMessage.success('企业照片上传完成');
    }
};

const onEnterprisePhotoRemove = async (index: number, image: any) => {
    console.log('企业照片删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要触发父组件的删除事件，让父组件知道有删除操作
    emit('enterprise-photo-remove', index, image);

    // 延迟一下再显示消息，避免与MultiImageUpload的消息冲突
    setTimeout(() => {
        ElMessage.success('企业照片删除完成');
    }, 100);
};

// 组件挂载时获取数据
onMounted(() => {
    console.log('FarmingInfo组件挂载，traceabilityId:', props.traceabilityId);
    // 确保数据数组已初始化
    if (!vaccineData.value) {
        vaccineData.value = [];
    }

    if (props.traceabilityId) {
        getFarmingInfo();
        getVaccineInfo(); // 组件挂载时获取保健信息
        getEnterpriseInfo(); // 组件挂载时获取企业信息
    } else {
        console.warn('traceabilityId为空，无法获取养殖信息');
        // 设置默认数据
        vaccineData.value = [
            { feedingDays: '35', immune_System: '兔瘟单苗', immune_Methods: '皮下注射' },
            { feedingDays: '40', immune_System: '巴二联苗', immune_Methods: '皮下注射' }
        ];
    }
});

// 监听traceabilityId变化
watch(() => props.traceabilityId, (newVal) => {
    if (newVal) {
        console.log('traceabilityId变化，重新获取数据:', newVal);
        getFarmingInfo();
        getVaccineInfo();
        getEnterpriseInfo();
    } else {
        // 如果traceabilityId为空，设置默认数据
        vaccineData.value = [
            { feedingDays: '35', immune_System: '兔瘟单苗', immune_Methods: '皮下注射' },
            { feedingDays: '40', immune_System: '巴二联苗', immune_Methods: '皮下注射' }
        ];
    }
});
</script>

<style scoped>
.farming-info {
    padding: 24px;
}

.info-section,
.vaccine-section,
.certificate-section,
.enterprise-section,
.photos-section {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.section-header h3 {
    margin: 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
}

.info-display {
    display: flex;
    gap: 40px;
}

.info-column {
    flex: 1;
}

.info-item {
    margin-bottom: 12px;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
}

.vaccine-section .info-display {
    display: block;
}

.vaccine-section .info-item {
    margin-bottom: 8px;
}

.upload-area {
    padding: 16px 0;
}

.certificate-section,
.photos-section {
    background: #f8f9fa;
}

.enterprise-section .info-display {
    display: block;
}

.enterprise-section .info-item {
    margin-bottom: 8px;
}
</style>